package cn.tedu.v1_2;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 聊天室 Version1 1.1
 * 功能：1.客户端--指定IP、端口号
 *      2.客户端给服务器发送文本
 *      3.客户端完成标准IO
 *【新增】4.捕获异常，打印异常信息---异常全部抓住，用户明确提示
 *      5.关闭socket
 */

public class Client {
    private Socket socket;
    public Client(){
        try {
            socket=new Socket("172.20.34.228",3636);
        }catch (UnknownHostException e){ //用户地址出问题异常
            System.out.println("IP地址有问题，请询问服务器端");
        } catch (IOException e) { //IO异常：连接失效，客户端主动退出
            System.out.println("客户端主动退出了：断开连接");
        }
    }
    public void start()  {
        OutputStream os=null;
        OutputStreamWriter osw=null;
        BufferedWriter bw=null;
        PrintWriter pw= null;  //置空流
        pw = null;
        try {
            os=socket.getOutputStream();
     //       InputStream is=socket.getInputStream();
            osw=new OutputStreamWriter(os,"UTF8");
    //        InputStreamReader isr=new InputStreamReader(is,"UTF8");
            bw=new BufferedWriter(osw);
      //      BufferedReader br=new BufferedReader(isr);
            pw=new PrintWriter(bw,true);
            System.out.println("客户端用户：请输入文字内容：");
            Scanner input=new Scanner(System.in);//测试--控制台输入文本
            while(true){//死循环----一直与服务器说话
                String say=input.nextLine();
                pw.println(say);//写出一行行文字
                System.out.println("写出完毕");
            }
        } catch(UnsupportedEncodingException e){
            System.out.println("客户端于服务器端：字符集不一致");
        } catch (IOException e) {
            System.out.println("客户端断开连接！");
        } finally {
            //关闭流   关闭socket
            try {
                if(pw!=null);
                pw.close();
                socket.close();
            } catch (Exception e) {
                System.out.println("客户端离开了");
            }
        }
    }

    public static void main(String[] args){
        Client client=new Client();
        client.start();
    }
}
